package com.example.shirodemo.config.exception;

import com.example.shirodemo.constant.HttpCode;
import com.example.shirodemo.dto.ResponseResult;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 绫小路
 * @date 2021/1/3 19:25
 * @description 全局异常
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(Exception.class)
  @ResponseBody
  public Object exception(Exception e) {
    log.error(e.getMessage());
    return null;
  }

  /**
   * 处理Shiro权限拦截异常
   * 如果返回JSON数据格式请加上 @ResponseBody注解
   * @Author Sans
   * @CreateTime 2019/6/15 13:35
   * @Return Map<Object> 返回结果集
   */
  @ResponseBody
  @ExceptionHandler(value = AuthorizationException.class)
  public Map<String,Object> defaultErrorHandler(){
    Map<String,Object> map = new HashMap<>();
    map.put("403","权限不足");
    return map;
  }

  /**
   * 断言异常处理
   */
  @ExceptionHandler(IllegalArgumentException.class)
  @ResponseBody
  public ResponseResult illegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
    addLoggerInfo(request, e.getMessage());
    return new ResponseResult(HttpCode.FAIL, e.getMessage());
  }

  @ExceptionHandler(RuntimeException.class)
  @ResponseBody
  public ResponseResult RuntimeException(RuntimeException e, HttpServletRequest request) {
    addLoggerInfo(request, e.getMessage());
    return new ResponseResult(HttpCode.FAIL, e.getMessage());
  }

  /**
   * 将请求参数打印到日志
   *
   * @param request
   * @param message
   */
  private void addLoggerInfo(HttpServletRequest request, String message) {
    log.error("异常请求-{} {} 远程地址-{} 异常信息-{}",
        request.getMethod(),
        request.getRequestURL(),
        request.getRemoteAddr(),
        message);
  }


}
